package com.matrix.draft.sockettest.protocoltcp.handler;

import com.matrix.draft.sockettest.protocoltcp.pojo.ProtocolMessage;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.nio.charset.StandardCharsets;

public class ServerHandler extends SimpleChannelInboundHandler<ProtocolMessage> {

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) {
        System.out.println("-----------  "+ctx.channel().remoteAddress()+"  -------------");
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ProtocolMessage msg) throws Exception {
        // 读取
        System.out.println("Got from client : "+ new String(msg.getContent(), StandardCharsets.UTF_8));
        // 回复
        byte[] bytes = ("收到收到Over").getBytes(StandardCharsets.UTF_8);
        ctx.writeAndFlush(new ProtocolMessage().setLen(bytes.length).setContent(bytes));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
